package com.songcha.library_network.util

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import java.util.Locale

class NetworkUtil {
    companion object{
        @JvmStatic
        fun isNetworkAvailable(context: Context?): Boolean {
            if (context == null) {
                return true
            }
            var manager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                var networkCapabilities: NetworkCapabilities? =
                    manager.getNetworkCapabilities(manager.activeNetwork)
                        ?: return false
                return networkCapabilities!!.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            } else {
                return manager.activeNetworkInfo?.isConnected ?: false
            }

        }

        @JvmStatic
        fun getIpAddress(context: Context):String{
            val wifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
            val ip = wifiManager.connectionInfo.ipAddress
            val ipAddress = String.format(Locale.getDefault(),"%d.%d.%d.%d",
                (ip and 0xff),(ip shr 8 and 0xff),(ip shr 16 and 0xff),(ip shr 24 and 0xff))
            return ipAddress
        }
    }
}